package com.example.hnvehicle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hnvehicle.bean.Users;
import com.example.hnvehicle.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Shunrai
 * @Date 2023/1/7 22:16
 * @Version 1.0
 * @Description
 */
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    private final static String ADMIN="管理员";
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用usersMapper中的方法查询数据库
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username",username);
        Users users = usersMapper.selectOne(usersQueryWrapper);
        //判断
        if(users==null){
            //数据库没有用户名，认证失败
            throw new UsernameNotFoundException("该用户名不存在");
        }
        List<GrantedAuthority> auths;
        if(users.getPower().equals(ADMIN)){
            auths= AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        }else {
            auths= AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_sale");
        }

        return new User(users.getUsername(),users.getPassword(),auths);
    }


}
